package com.lanzuo.yxd.scanner.service;

import com.lanzuo.yxd.scanner.config.LaneConfig;
import com.lanzuo.yxd.scanner.config.LaneConfigList;
import com.lanzuo.yxd.scanner.config.ScannerConfig;
import com.lanzuo.yxd.scanner.scanner.ScanResultHolder;
import com.lanzuo.yxd.scanner.scanner.ScannerClient;
import com.lanzuo.yxd.scanner.scanner.ScannerWaitNotifyCoordinator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeoutException;

@Slf4j
@Service
public class TouchScannerService {

    @Resource
    LaneConfigList laneConfigList;

    @Resource
    ScannerWaitNotifyCoordinator coordinator;

    public void scan() {
        List<LaneConfig> configs = laneConfigList.getConfigs();
        for (LaneConfig laneConfig : configs) {
            ScannerConfig topScanner = laneConfig.getScanner().stream().filter(v -> "top".equalsIgnoreCase(v.getPosition())).findFirst().orElse(null);
            ScannerConfig bottomScanner = laneConfig.getScanner().stream().filter(v -> "bottom".equalsIgnoreCase(v.getPosition())).findFirst().orElse(null);

            Integer lane = laneConfig.getLaneNo();
            Boolean topResult = false;
            // === 扫 top ===
            if (topScanner != null) {
                ScanResultHolder topHolder = coordinator.createHolder(lane, topScanner.getIp(), topScanner.getPosition());
                // 先扫上面的码
                ScannerClient topClient = new ScannerClient(lane, topScanner.getIp(), topScanner.getPosition());
                topClient.sendT1();

                try {
                    // 5秒超时
                    topResult = topHolder.waitForResult(15000);
                    log.info("Lane-{}-Top 扫码校验结果: {}", lane, topResult);
                } catch (TimeoutException | InterruptedException e) {
                    log.warn("Lane-{}-Top 扫码校验超时", lane);
                }

                topClient.destroy();
            }

            // === 扫 bottom ===
            if (!topResult && bottomScanner != null) {
                ScanResultHolder bottomHolder = coordinator.createHolder(lane, bottomScanner.getIp(), bottomScanner.getPosition());
                // 先扫上面的码
                ScannerClient bottomClient = new ScannerClient(lane, bottomScanner.getIp(), bottomScanner.getPosition());
                bottomClient.sendT1();

                try {
                    // 5秒超时
                    topResult = topResult || bottomHolder.waitForResult(15000);
                    log.info("Lane-{}-Bottom 扫码校验结果: {}", lane, topResult);
                } catch (TimeoutException e) {
                    log.warn("Lane-{}-Bottom 扫码校验超时", lane);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                bottomClient.destroy();
            }
        }
    }
}
